/*
* ===================================================
*
*       Filename:  mapping.c
*
*
*        Created:  10/11/2011 07:02:02 PM
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  durand_y, <durand.yoan@gmail.com>
*
* ===================================================
*/
#include "malloc.h"

s_map      *g_map_list = NULL;

static void        new_map(size_t  size,
						   void    *ptr,
						   char    *s)
{
    s_block         *b = NULL;
    s_map           *aux = NULL;
    s_map           *p = NULL;

    aux = ptr;
    ptr = s;
    b = ptr;
    aux->block = b;
    aux->block->size = size;
    aux->block->state = NON_FREE;
    aux->block->next = NULL;
    s = s + sizeof (s_block);
    ptr = s;
    aux->block->end = ptr;
    p = g_map_list;
    if (p->next_map != NULL)
    {
        while (p->next_map != NULL)
        p = p->next_map;
    }
            p->next_map = aux;
            aux->next_map = NULL;
}

void                create_map(size_t size)
{
    s_block         *b = NULL;
    void            *ptr = NULL;
    char            *test = NULL;

    if ((ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS
		| MAP_PRIVATE, -1, 0)) !=  MAP_FAILED)
    {
        test = ptr;
        test = test + sizeof (s_map);
        if (g_map_list == NULL)
        {
            g_map_list = ptr;
            ptr = test;
            b = ptr;
            g_map_list->block = b;
            g_map_list->block->size = size;
            g_map_list->block->state = NON_FREE;
            g_map_list->block->next = NULL;
            test = test + sizeof (s_block);
            ptr = test;
            g_map_list->block->end = ptr;
            g_map_list->next_map = NULL;
        }
        else
            new_map(size, ptr, test);
    }
}
